﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Xml;

/*
    LayerBuilder - C# code generator for MS SQLCE / MS SQLServer / OLEDB Layers.
    Copyright (C) 2009 1.xx matricrix
    Copyright (C) 2011 2.xx matricrix
 
    http://layerbuilder.codeplex.com/
    matricrix@gmail.com
   
    License:  GNU General Public License version 2 (GPLv2)
*/

namespace LayerBuilder
{
    /// <summary>
    /// 
    /// </summary>
    public partial class MainForm : Form
    {
        private List<TableView> _tables = new List<TableView>();
        private Dictionary<string, ProjectProperty> _projects = new Dictionary<string, ProjectProperty>();

        /// <summary>
        /// 
        /// </summary>
        public class TableView
        {
            public bool Export { set; get; }
            public string TableName { set; get; }
            public string ClassName { set; get; }
        }

        /// <summary>
        /// 
        /// </summary>
        public class ProjectProperty
        {
            public string cbProjects;
            public string cbSqlCEFile;
            public string tcSource;
            public string cbSqlSrvInstance;
            public string cbSqlSrvDB;
            public string cbSqlSrvUsr;
            public string cbNamespace;
            public string cbSaveAsFolder;
        }

        /// <summary>
        /// 
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            //
            this.LoadSettings();

            //
            this.lVersion.Text = string.Format("version {0}", Application.ProductVersion);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.SaveSettings();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvTables_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.EnumColumns();
            this.EnumIndexes();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void llAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AboutBox aboutBox = new AboutBox();
            aboutBox.ShowDialog(this);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void llCopyright_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CopyrightBox copyright = new CopyrightBox();
            copyright.ShowDialog(this);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void llFAQ_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FAQBox faq = new FAQBox();
            faq.ShowDialog(this);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private bool EnumTables()
        {
            bool bOk = false;

            try
            {
                this.toolStripStatusMessage.Text = "Enum tables...";

                this.tvTables.Nodes.Clear();
                this.tvColumns.Nodes.Clear();
                this.tvIndexes.Nodes.Clear();
                this._tables = new List<TableView>();

                DataSet dsTables = null;

                switch ((string)this.tcSource.SelectedTab.Tag)
                {
                    case Layer.SOURCE_TYPE_MSSQLCE:
                        dsTables = Microsoft.ApplicationBlocks.Data.CE.SqlHelper.ExecuteDataset(this.GetConnectionString(), CommandType.Text, "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME");
                        break;

                    case Layer.SOURCE_TYPE_MSSQLSRV:
                        dsTables = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(this.GetConnectionString(), CommandType.Text, "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME");
                        break;

                    case Layer.SOURCE_TYPE_OLEDB:
                        break;
                }

                DataTable dtTables = dsTables.Tables[0];
                foreach (DataRow drTable in dtTables.Rows)
                {
                    this.tvTables.Nodes.Add((string)drTable["TABLE_NAME"]);
                    this._tables.Add(new TableView(){ Export = false, TableName = (string)drTable["TABLE_NAME"], ClassName = (string)drTable["TABLE_NAME"]});
                }

                bOk = true;
            }
            catch(Exception ex)
            {
                this.toolStripStatusMessage.Text = "ERROR -> " + ex.Message;
                bOk = false;
            }

            return bOk;
        }

        /// <summary>
        /// 
        /// </summary>
        private bool EnumColumns()
        {
            bool bOk = false;

            try
            {
                this.toolStripStatusMessage.Text = "Enum PK columns...";

                List<string> keyFieldsCollection = new List<string>();
                DataSet dsKeyColumns = null;
                switch ((string)this.tcSource.SelectedTab.Tag)
                {
                    case Layer.SOURCE_TYPE_MSSQLCE:
                        dsKeyColumns = Microsoft.ApplicationBlocks.Data.CE.SqlHelper.ExecuteDataset(this.GetConnectionString(), CommandType.Text, "SELECT KU.COLUMN_NAME, KU.ORDINAL_POSITION FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC  JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KU ON  KU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME   AND KU.TABLE_NAME = TC.TABLE_NAME WHERE TC.TABLE_NAME = @TABLE_NAME AND TC.CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY KU.ORDINAL_POSITION", new System.Data.SqlServerCe.SqlCeParameter("@TABLE_NAME", this.tvTables.SelectedNode.Text));
                        break;

                    case Layer.SOURCE_TYPE_MSSQLSRV:
                        dsKeyColumns = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(this.GetConnectionString(), CommandType.Text, "SELECT KU.COLUMN_NAME, KU.ORDINAL_POSITION FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC  JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KU ON  KU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME   AND KU.TABLE_NAME = TC.TABLE_NAME WHERE TC.TABLE_NAME = @TABLE_NAME AND TC.CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY KU.ORDINAL_POSITION", new System.Data.SqlClient.SqlParameter("@TABLE_NAME", this.tvTables.SelectedNode.Text));
                        break;

                    case Layer.SOURCE_TYPE_OLEDB:
                        break;
                }
                
                DataTable dtKeyColumns = dsKeyColumns.Tables[0];
                foreach (DataRow drkeyColumns in dtKeyColumns.Rows)
                    keyFieldsCollection.Add((string)drkeyColumns["COLUMN_NAME"]);

                this.toolStripStatusMessage.Text = "Enum columns...";

                this.tvColumns.Nodes.Clear();
                DataSet dsColumns = null;               
                switch ((string)this.tcSource.SelectedTab.Tag)
                {
                    case Layer.SOURCE_TYPE_MSSQLCE:
                        dsColumns = Microsoft.ApplicationBlocks.Data.CE.SqlHelper.ExecuteDataset(this.GetConnectionString(), CommandType.Text, "SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TABLE_NAME ORDER BY ORDINAL_POSITION", new System.Data.SqlServerCe.SqlCeParameter("@TABLE_NAME", this.tvTables.SelectedNode.Text));
                        break;

                    case Layer.SOURCE_TYPE_MSSQLSRV:
                        dsColumns = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(this.GetConnectionString(), CommandType.Text, "SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TABLE_NAME ORDER BY ORDINAL_POSITION", new System.Data.SqlClient.SqlParameter("@TABLE_NAME", this.tvTables.SelectedNode.Text));
                        break;

                    case Layer.SOURCE_TYPE_OLEDB:
                        break;
                }
                
                DataTable dtColumns = dsColumns.Tables[0];
                foreach (DataRow drColumns in dtColumns.Rows)
                    this.tvColumns.Nodes.Add((string)drColumns["COLUMN_NAME"], string.Format("{0} ({1}) {2}", drColumns["COLUMN_NAME"], drColumns["DATA_TYPE"], (((string)drColumns["IS_NULLABLE"]) == "NO" ? "NOT NULL" : "NULL")), (keyFieldsCollection.Contains((string)drColumns["COLUMN_NAME"]) ? 0 : 2));

                bOk = true;
            }
            catch(Exception ex)
            {
                this.toolStripStatusMessage.Text = "ERROR -> " + ex.Message;
            }

            return bOk;
        }

        /// <summary>
        /// 
        /// </summary>
        private bool EnumIndexes()
        {
            bool bOk = false;

            try
            {
                this.toolStripStatusMessage.Text = "Enum indexes...";

                this.tvIndexes.Nodes.Clear();

                DataSet dsIndexes = null; 
                switch ((string)this.tcSource.SelectedTab.Tag)
                {
                    case Layer.SOURCE_TYPE_MSSQLCE:
                        dsIndexes = Microsoft.ApplicationBlocks.Data.CE.SqlHelper.ExecuteDataset(this.GetConnectionString(), CommandType.Text, "SELECT DISTINCT INDEX_NAME, PRIMARY_KEY FROM INFORMATION_SCHEMA.INDEXES WHERE TABLE_NAME = @TABLE_NAME", new System.Data.SqlServerCe.SqlCeParameter("@TABLE_NAME", this.tvTables.SelectedNode.Text));
                        break;

                    case Layer.SOURCE_TYPE_MSSQLSRV:
                        dsIndexes = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(this.GetConnectionString(), CommandType.Text, "SELECT IDX.NAME INDEX_NAME, IDX.IS_PRIMARY_KEY PRIMARY_KEY FROM SYS.OBJECTS OBJ JOIN SYS.INDEXES IDX ON IDX.OBJECT_ID = OBJ.OBJECT_ID WHERE OBJ.NAME = @TABLE_NAME", new System.Data.SqlClient.SqlParameter("@TABLE_NAME", this.tvTables.SelectedNode.Text));
                        break;

                    case Layer.SOURCE_TYPE_OLEDB:
                        break;
                }

                DataTable dtIndexes = dsIndexes.Tables[0];
                foreach (DataRow drIndexes in dtIndexes.Rows)
                    this.tvIndexes.Nodes.Add((string)drIndexes["INDEX_NAME"]);

                bOk = true;
            }
            catch(Exception ex)
            {
                this.toolStripStatusMessage.Text = "ERROR -> " + ex.Message;
            }

            return bOk;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbMSSQLCE_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbMSSQLCE.Checked && (string)this.tcSource.SelectedTab.Tag != Layer.SOURCE_TYPE_MSSQLCE)
            {
                this.tcSource.SelectedTab.Tag = Layer.SOURCE_TYPE_MSSQLCE;
                this.tcSource.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbMSSQLSRV_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbMSSQLSRV.Checked && (string)this.tcSource.SelectedTab.Tag != Layer.SOURCE_TYPE_MSSQLSRV)
            {
                this.tcSource.SelectedTab.Tag = Layer.SOURCE_TYPE_MSSQLSRV;
                this.tcSource.SelectedIndex = 1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbOLEDB_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbOLEDB.Checked && (string)this.tcSource.SelectedTab.Tag != Layer.SOURCE_TYPE_OLEDB)
            {
                this.tcSource.SelectedTab.Tag = Layer.SOURCE_TYPE_OLEDB;
                this.tcSource.SelectedIndex = 2;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tcSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch ((string)this.tcSource.SelectedTab.Tag)
            {
                case Layer.SOURCE_TYPE_MSSQLCE:
                    this.rbMSSQLCE.Checked = true;
                    break;

                case Layer.SOURCE_TYPE_MSSQLSRV:
                    this.rbMSSQLSRV.Checked = true;
                    break;

                case Layer.SOURCE_TYPE_OLEDB:
                    this.rbOLEDB.Checked = true;
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bNextSource_Click(object sender, EventArgs e)
        {
            this.tcSteps.SelectedIndex = 1;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bPreviosTables_Click(object sender, EventArgs e)
        {
            this.tcSteps.SelectedIndex = 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bNextTables_Click(object sender, EventArgs e)
        {
            this.tcSteps.SelectedIndex = 2;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bPreviuosTarget_Click(object sender, EventArgs e)
        {
            this.tcSteps.SelectedIndex = 1;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bGenerateTarget_Click(object sender, EventArgs e)
        {
            if (this.GenerateClasses())
                this.CacheSettings();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bSQLCEDatabaseSearch_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog.ShowDialog(this) == DialogResult.OK)
                this.cbSqlCEFile.Text = this.openFileDialog.FileName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bOutputFolderBrowse_Click(object sender, EventArgs e)
        {
            if (this.folderBrowserDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                this.cbSaveAsFolder.Text = this.folderBrowserDialog.SelectedPath;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbSQLSrvTrusted_CheckedChanged(object sender, EventArgs e)
        {
            this.pSQLSrvUsrPwdInfo.Enabled = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbSQLSrvNoTrusted_CheckedChanged(object sender, EventArgs e)
        {
            this.pSQLSrvUsrPwdInfo.Enabled = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tcSteps_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.tcSteps.SelectedIndex)
            {
                case 0:
                    break;
                case 1:
                    this.EnumTables();
                    break;
                case 2:
                    this.EnumTables();
                    break;
            }

            this.dgvTables.DataSource = this._tables;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbProjects_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.LoadProject();
        }


        /// <summary>
        /// 
        /// </summary>
        private void LoadSettings()
        {
            try
            {
                if (File.Exists(".\\Settings.xml"))
                {
                    FileStream fs = new FileStream(".\\Settings.xml", FileMode.Open);

                    XmlTextReader xtr = new XmlTextReader(fs);

                    bool settingsElement = false;
                    string defaultProject = string.Empty;

                    while (xtr.Read())
                    {
                        switch (xtr.NodeType)
                        {
                            case XmlNodeType.Element:

                                switch (xtr.Name.ToUpper())
                                {
                                    case "SETTINGS":
                                        settingsElement = true;
                                        break;

                                    case "HISTORY_PROJECTS":
                                        while (settingsElement && xtr.Read())
                                        {
                                            if (xtr.IsStartElement())
                                            {
                                                if (xtr.NodeType == XmlNodeType.Element && xtr.Name.ToUpper() == "PROJECT")
                                                    this.cbProjects.Items.Add(HttpUtility.UrlDecode(xtr.ReadElementContentAsString()));
                                            }
                                            else
                                                break;
                                        }
                                        break;

                                    case "HISTORY_LAST_PROJECT":
                                        if (settingsElement)
                                            defaultProject = HttpUtility.UrlDecode(xtr.ReadElementContentAsString());
                                        break;

                                    case "HISTORY_SQLCE_FILES":
                                        while (settingsElement && xtr.Read())
                                        {
                                            if (xtr.IsStartElement())
                                            {
                                                if (xtr.NodeType == XmlNodeType.Element && xtr.Name.ToUpper() == "FILE")
                                                    this.cbSqlCEFile.Items.Add(HttpUtility.UrlDecode(xtr.ReadElementContentAsString()));
                                            }
                                            else
                                                break;
                                        }
                                        break;

                                    case "HISTORY_SQLSRV_INSTANCES":
                                        while (settingsElement && xtr.Read())
                                        {
                                            if (xtr.IsStartElement())
                                            {
                                                if (xtr.NodeType == XmlNodeType.Element && xtr.Name.ToUpper() == "INSTANCE")
                                                    this.cbSqlSrvInstance.Items.Add(HttpUtility.UrlDecode(xtr.ReadElementContentAsString()));
                                            }
                                            else
                                                break;
                                        }
                                        break;

                                    case "HISTORY_SQLSRV_DBS":
                                        while (settingsElement && xtr.Read())
                                        {
                                            if (xtr.IsStartElement())
                                            {
                                                if (xtr.NodeType == XmlNodeType.Element && xtr.Name.ToUpper() == "DB")
                                                    this.cbSqlSrvDB.Items.Add(HttpUtility.UrlDecode(xtr.ReadElementContentAsString()));
                                            }
                                            else
                                                break;
                                        }
                                        break;

                                    case "HISTORY_SQLSRV_USERNAMES":
                                        while (settingsElement && xtr.Read())
                                        {
                                            if (xtr.IsStartElement())
                                            {
                                                if (xtr.NodeType == XmlNodeType.Element && xtr.Name.ToUpper() == "USERNAME")
                                                    this.cbSqlSrvUsr.Items.Add(HttpUtility.UrlDecode(xtr.ReadElementContentAsString()));
                                            }
                                            else
                                                break;
                                        }
                                        break;

                                    case "HISTORY_NAMESPACES":
                                        while (settingsElement && xtr.Read())
                                        {
                                            if (xtr.IsStartElement())
                                            {
                                                if (xtr.NodeType == XmlNodeType.Element && xtr.Name.ToUpper() == "NAMESPACE")
                                                    this.cbNamespace.Items.Add(HttpUtility.UrlDecode(xtr.ReadElementContentAsString()));
                                            }
                                            else
                                                break;
                                        }
                                        break;

                                    case "HISTORY_EXPORT_FOLDERS":
                                        while (settingsElement && xtr.Read())
                                        {
                                            if (xtr.IsStartElement())
                                            {
                                                if (xtr.NodeType == XmlNodeType.Element && xtr.Name.ToUpper() == "FOLDER")
                                                    this.cbSaveAsFolder.Items.Add(HttpUtility.UrlDecode(xtr.ReadElementContentAsString()));
                                            }
                                            else
                                                break;
                                        }
                                        break;

                                    case "HISTORY_PROJECTS_DATA":
                                        while (settingsElement && xtr.Read())
                                        {
                                            if (xtr.IsStartElement())
                                            {
                                                if (xtr.NodeType == XmlNodeType.Element && xtr.Name.ToUpper() == "DATA")
                                                {
                                                    ProjectProperty pp = new ProjectProperty();

                                                    while (settingsElement && xtr.Read())
                                                    {
                                                        if (xtr.IsStartElement())
                                                        {
                                                            if (xtr.NodeType == XmlNodeType.Element)
                                                            {
                                                                switch (xtr.Name.ToUpper())
                                                                {
                                                                    case "CBNAMESPACE":
                                                                        pp.cbNamespace = HttpUtility.UrlDecode(xtr.ReadElementContentAsString());
                                                                        break;

                                                                    case "CBPROJECTS":
                                                                        pp.cbProjects = HttpUtility.UrlDecode(xtr.ReadElementContentAsString());
                                                                        break;

                                                                    case "CBSAVEASFOLDER":
                                                                        pp.cbSaveAsFolder = HttpUtility.UrlDecode(xtr.ReadElementContentAsString());
                                                                        break;

                                                                    case "CBSQLCEFILE":
                                                                        pp.cbSqlCEFile = HttpUtility.UrlDecode(xtr.ReadElementContentAsString());
                                                                        break;

                                                                    case "CBSQLSRVDB":
                                                                        pp.cbSqlSrvDB = HttpUtility.UrlDecode(xtr.ReadElementContentAsString());
                                                                        break;

                                                                    case "CBSQLSRVINSTANCE":
                                                                        pp.cbSqlSrvInstance = HttpUtility.UrlDecode(xtr.ReadElementContentAsString());
                                                                        break;

                                                                    case "CBSQLSRVUSR":
                                                                        pp.cbSqlSrvUsr = HttpUtility.UrlDecode(xtr.ReadElementContentAsString());
                                                                        break;

                                                                    case "TCSOURCE":
                                                                        pp.tcSource = HttpUtility.UrlDecode(xtr.ReadElementContentAsString());
                                                                        break;
                                                                }
                                                            }
                                                        }
                                                    }

                                                    this._projects.Add(pp.cbProjects, pp);
                                                }
                                            }
                                            else
                                                break;
                                        }
                                        break;
                                }

                                break;
                        }

                    }

                    xtr.Close();

                    // HISTORY_LAST_PROJECT
                    if (this.cbProjects.Items.Contains(defaultProject))
                        this.cbProjects.Text = defaultProject;
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void SaveSettings()
        {
            try
            {
                FileStream fs = new FileStream(".\\Settings.xml", FileMode.Create);

                XmlTextWriter xtw = new XmlTextWriter(fs, Encoding.UTF8);
                xtw.Formatting = Formatting.Indented;
                xtw.IndentChar = '\t';

                xtw.WriteStartDocument();

                xtw.WriteComment("C# LayerBuilder Settings");

                xtw.WriteStartElement("SETTINGS");

                #region HISTORY_PROJECTS
                xtw.WriteStartElement("HISTORY_PROJECTS");
                foreach (string s in this.cbProjects.Items)
                {
                    xtw.WriteStartElement("PROJECT");
                    xtw.WriteString(HttpUtility.UrlEncode(s));
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion

                #region HISTORY_LAST_PROJECT
                xtw.WriteStartElement("HISTORY_LAST_PROJECT");
                xtw.WriteString(HttpUtility.UrlEncode(this.cbProjects.Text));
                xtw.WriteEndElement();
                #endregion

                #region HISTORY_SQLCE_FILES
                xtw.WriteStartElement("HISTORY_SQLCE_FILES");
                foreach (string s in this.cbSqlCEFile.Items)
                {
                    xtw.WriteStartElement("FILE");
                    xtw.WriteString(HttpUtility.UrlEncode(s));
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion

                #region HISTORY_SQLSRV_INSTANCE
                xtw.WriteStartElement("HISTORY_SQLSRV_INSTANCES");
                foreach (string s in this.cbSqlSrvInstance.Items)
                {
                    xtw.WriteStartElement("INSTANCE");
                    xtw.WriteString(HttpUtility.UrlEncode(s));
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion

                #region HISTORY_SQLSRV_DB
                xtw.WriteStartElement("HISTORY_SQLSRV_DBS");
                foreach (string s in this.cbSqlSrvDB.Items)
                {
                    xtw.WriteStartElement("DB");
                    xtw.WriteString(HttpUtility.UrlEncode(s));
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion

                #region HISTORY_SQLSRV_USERNAME
                xtw.WriteStartElement("HISTORY_SQLSRV_USERNAMES");
                foreach (string s in this.cbSqlSrvUsr.Items)
                {
                    xtw.WriteStartElement("USERNAMES");
                    xtw.WriteString(HttpUtility.UrlEncode(s));
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion

                #region HISTORY_NAMESPACE
                xtw.WriteStartElement("HISTORY_NAMESPACES");
                foreach (string s in this.cbNamespace.Items)
                {
                    xtw.WriteStartElement("NAMESPACE");
                    xtw.WriteString(HttpUtility.UrlEncode(s));
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion

                #region HISTORY_EXPORT_FOLDERS
                xtw.WriteStartElement("HISTORY_EXPORT_FOLDERS");
                foreach (string s in this.cbSaveAsFolder.Items)
                {
                    xtw.WriteStartElement("FOLDER");
                    xtw.WriteString(HttpUtility.UrlEncode(s));
                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion

                #region HISTORY_PROJECTS_DATA
                xtw.WriteStartElement("HISTORY_PROJECTS_DATA");
                foreach (KeyValuePair<string, ProjectProperty> kvp in this._projects)
                {
                    xtw.WriteStartElement("DATA");

                    xtw.WriteStartElement("CBNAMESPACE");
                    xtw.WriteString(HttpUtility.UrlEncode(kvp.Value.cbNamespace));
                    xtw.WriteEndElement();

                    xtw.WriteStartElement("CBPROJECTS");
                    xtw.WriteString(HttpUtility.UrlEncode(kvp.Value.cbProjects));
                    xtw.WriteEndElement();

                    xtw.WriteStartElement("CBSAVEASFOLDER");
                    xtw.WriteString(HttpUtility.UrlEncode(kvp.Value.cbSaveAsFolder));
                    xtw.WriteEndElement();

                    xtw.WriteStartElement("CBSQLCEFILE");
                    xtw.WriteString(HttpUtility.UrlEncode(kvp.Value.cbSqlCEFile));
                    xtw.WriteEndElement();

                    xtw.WriteStartElement("CBSQLSRVDB");
                    xtw.WriteString(HttpUtility.UrlEncode(kvp.Value.cbSqlSrvDB));
                    xtw.WriteEndElement();

                    xtw.WriteStartElement("CBSQLSRVINSTANCE");
                    xtw.WriteString(HttpUtility.UrlEncode(kvp.Value.cbSqlSrvInstance));
                    xtw.WriteEndElement();

                    xtw.WriteStartElement("CBSQLSRVUSR");
                    xtw.WriteString(HttpUtility.UrlEncode(kvp.Value.cbSqlSrvUsr));
                    xtw.WriteEndElement();

                    xtw.WriteStartElement("TCSOURCE");
                    xtw.WriteString(HttpUtility.UrlEncode(kvp.Value.tcSource));
                    xtw.WriteEndElement();

                    xtw.WriteEndElement();
                }
                xtw.WriteEndElement();
                #endregion

                xtw.WriteEndElement();

                xtw.WriteEndDocument();

                xtw.Flush();

                xtw.Close();
            }
            catch
            {
            }

        }

        /// <summary>
        /// 
        /// </summary>
        private void CacheSettings()
        {
            //
            if (!this.cbNamespace.Items.Contains(this.cbNamespace.Text))
                this.cbNamespace.Items.Add(this.cbNamespace.Text);

            if (!this.cbProjects.Items.Contains(this.cbProjects.Text))
                this.cbProjects.Items.Add(this.cbProjects.Text);

            if (!this.cbSaveAsFolder.Items.Contains(this.cbSaveAsFolder.Text))
                this.cbSaveAsFolder.Items.Add(this.cbSaveAsFolder.Text);

            if (!this.cbSqlCEFile.Items.Contains(this.cbSqlCEFile.Text))
                this.cbSqlCEFile.Items.Add(this.cbSqlCEFile.Text);

            if (!this.cbSqlSrvDB.Items.Contains(this.cbSqlSrvDB.Text))
                this.cbSqlSrvDB.Items.Add(this.cbSqlSrvDB.Text);

            if (!this.cbSqlSrvInstance.Items.Contains(this.cbSqlSrvInstance.Text))
                this.cbSqlSrvInstance.Items.Add(this.cbSqlSrvInstance.Text);

            if (!this.cbSqlSrvUsr.Items.Contains(this.cbSqlSrvUsr.Text))
                this.cbSqlSrvUsr.Items.Add(this.cbSqlSrvUsr.Text);

            // HISTORY_PROJECTS_DATA
            if (!this._projects.ContainsKey(this.cbProjects.Text))
                this._projects.Add(this.cbProjects.Text, null);

            this._projects[this.cbProjects.Text] = new ProjectProperty()
                {
                    cbNamespace = this.cbNamespace.Text,
                    cbProjects = this.cbProjects.Text,
                    cbSaveAsFolder = this.cbSaveAsFolder.Text,
                    cbSqlCEFile = this.cbSqlCEFile.Text,
                    cbSqlSrvDB = this.cbSqlSrvDB.Text,
                    cbSqlSrvInstance = this.cbSqlSrvInstance.Text,
                    cbSqlSrvUsr = this.cbSqlSrvUsr.Text,
                    tcSource = (string)this.tcSource.SelectedTab.Tag
                };
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private string GetConnectionString()
        {
            string sConnectionString = string.Empty;

            switch ((string)this.tcSource.SelectedTab.Tag)
            {
                case Layer.SOURCE_TYPE_MSSQLCE:
                    sConnectionString = "Data Source=" + this.cbSqlCEFile.Text + ";Persist Security Info=False;";
                    break;

                case Layer.SOURCE_TYPE_MSSQLSRV:
                    if (this.rbSQLSrvNoTrusted.Checked)
                        sConnectionString = "Server=" + this.cbSqlSrvInstance.Text + ";Database=" + this.cbSqlSrvDB.Text + ";User ID=" + this.cbSqlSrvUsr.Text + ";Password=" + this.tbSqlSrvPwd.Text + ";Trusted_Connection=False";
                    else
                        sConnectionString = "Server=" + this.cbSqlSrvInstance.Text + ";Database=" + this.cbSqlSrvDB.Text + ";Trusted_Connection=True";
                    break;

                case Layer.SOURCE_TYPE_OLEDB:
                    break;
            }

            return sConnectionString;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private bool GenerateClasses()
        {
            Layer layer;
            try
            {
                foreach (DataGridViewRow dgvRow in this.dgvTables.Rows)
                {
                    TableView tableView = (TableView)dgvRow.DataBoundItem;
                    if (tableView.Export)
                    {
                        layer = new Layer();

                        layer.SourceType = (string)this.tcSource.SelectedTab.Tag;
                        layer.ConnectionString = this.GetConnectionString();
                        layer.Namespace = this.cbNamespace.Text;
                        layer.OutputFolder = this.cbSaveAsFolder.Text;
                        layer.UseDBLocalizedNamespace = this.cbDBNamespace.Checked;
                        layer.Table = tableView.TableName;
                        layer.ClassName = tableView.ClassName;

                        layer.Generate();
                    }
                }

                this.toolStripStatusMessage.Text = "CODE GENERATED!";

                return true;
            }
            catch (Exception ex)
            {
                this.toolStripStatusMessage.Text = "ERROR -> " + ex.Message;

                return false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadProject()
        {
            if (this._projects.ContainsKey(this.cbProjects.Text))
            {
                ProjectProperty pp = this._projects[this.cbProjects.Text];

                this.cbNamespace.Text = pp.cbNamespace;
                this.cbProjects.Text = pp.cbProjects;
                this.cbSaveAsFolder.Text = pp.cbSaveAsFolder;
                this.cbSqlCEFile.Text = pp.cbSqlCEFile;
                this.cbSqlSrvDB.Text = pp.cbSqlSrvDB;
                this.cbSqlSrvInstance.Text = pp.cbSqlSrvInstance;
                this.cbSqlSrvUsr.Text = pp.cbSqlSrvUsr;

                switch (pp.tcSource)
                {
                    case Layer.SOURCE_TYPE_MSSQLCE:
                        this.rbMSSQLCE.Checked = true;
                        break;

                    case Layer.SOURCE_TYPE_MSSQLSRV:
                        this.rbMSSQLSRV.Checked = true;
                        break;

                    case Layer.SOURCE_TYPE_OLEDB:
                        this.rbOLEDB.Checked = true;
                        break;
                }
            }
        }
    }
}
 